package myapps.ttclient.activity;

import java.util.ArrayList;

import myapps.ttclient.adapter.FileExplorerArrayAdapter;
import myapps.ttclient.app.TTClientApplication;
import myapps.ttclient.baseclass_and_interface.TTConnectionStateChangedListener;
import myapps.ttclient.baseclass_and_interface.TTClientMessage;
import myapps.ttclient.baseclass_and_interface.TTClientMessageReceiver;
import myapps.ttclient.protocol.message.FileExploreRequestMessage;
import myapps.ttclient.protocol.message.FileExploreResponseMessage;
import myapps.ttclient.struct.FileInformationStruct;
import myapps.ttclient.GlobalVariables;
import myapps.ttclient.R;


import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class FileExplorerActivity extends Activity implements TTClientMessageReceiver, TTConnectionStateChangedListener,OnItemClickListener
{
	private static final int REFRESH_MENU_ITEM_ID = 0;
	private static final int EXPLORE_ROOTS_MENU_ITEM_ID = 1;
	private static final int BACK_MENU_ITEM_ID = 2;

	private TTClientApplication application;
	private SharedPreferences preferences;

	private String directory;
	// ""
	// "C:\\"
	// "C:\\Windows\\"


	//private ArrayList<String> files;
	//private ArrayAdapter<String> adapter;

	private ArrayList<FileInformationStruct> fileInfos;
	private ArrayAdapter<FileInformationStruct> adapter;


	private ListView listView;

	private TextView tvDirectory;
	private TextView tvDirectoryLabel;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		this.application = (TTClientApplication) this.getApplication();

		this.preferences = this.application.getPreferences();

		this.setContentView(R.layout.fileexplorer);

		this.listView = (ListView) this.findViewById(R.id.files);

		this.tvDirectory = (TextView) this.findViewById(R.id.directory);
		this.tvDirectory.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				AlertDialog.Builder builder = new AlertDialog.Builder(FileExplorerActivity.this);

				String message = FileExplorerActivity.this.directory;
				if("".compareTo(message) == 0) {
					message = "ROOT";
				}
				
				builder
				.setTitle("Current Location")
				.setMessage(message)
				.setCancelable(false)
				.setPositiveButton("Close", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {

					}
				});
				AlertDialog alert = builder.create();
				alert.show();
			}
		});

		this.tvDirectoryLabel = (TextView) this.findViewById(R.id.directoryLabel);
		this.tvDirectoryLabel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				AlertDialog.Builder builder = new AlertDialog.Builder(FileExplorerActivity.this);

				String message = FileExplorerActivity.this.directory;
				if("".compareTo(message) == 0) {
					message = "ROOT";
				}
				
				builder
				.setTitle("Current Location")
				.setMessage(message)
				.setCancelable(false)
				.setPositiveButton("Close", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {

					}
				});
				AlertDialog alert = builder.create();
				alert.show();
			}
		});

		//this.files = new ArrayList<String>();
		//this.adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, this.files);
		//this.adapter = new ArrayAdapter<String>(this, R.layout.rowlayout, R.id.label, this.files);

		this.fileInfos = new ArrayList<FileInformationStruct>();

		this.adapter = new FileExplorerArrayAdapter(this, R.layout.fileexplorer_rowlayout, fileInfos);

		this.listView.setAdapter(this.adapter);

		this.listView.setOnItemClickListener(this);

		this.directory = this.preferences.getString("fileExplore_directory", "");
	}

	@Override
	protected void onResume() {
		super.onResume();

		this.application.registerMessageReceiver(this);
		this.application.registerConnectionStateChangedListener(this);

		this.directory = this.preferences.getString("fileExplore_directory", "");
		
		this.refresh();
	}
	
	@Override
	protected void onPause() {
		super.onPause();

		this.application.unregisterMessageReceiver(this);
		this.application.unregisterConnectionStateChangedListener(this);

		Editor editor = this.preferences.edit();
		editor.putString("fileExplore_directory", this.directory);
		editor.commit();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(Menu.NONE, REFRESH_MENU_ITEM_ID, Menu.NONE, "Refresh");
		menu.add(Menu.NONE, EXPLORE_ROOTS_MENU_ITEM_ID, Menu.NONE, "Explorer Root");
		menu.add(Menu.NONE, BACK_MENU_ITEM_ID, Menu.NONE, "Back Screen");

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case REFRESH_MENU_ITEM_ID:
			this.refreshConnection();
			break;
			
		case EXPLORE_ROOTS_MENU_ITEM_ID:
			this.exploreRoots();
			break;
			
		case BACK_MENU_ITEM_ID:
			this.finish();
			break;
		}

		this.application.vibrate(50);
		
		return true;
	}

	private void up() {
		String dir = this.directory;

		int idx_1 = dir.lastIndexOf("\\");

		if(idx_1 != -1)	{ // Exclude ""
			int idx_2 = dir.indexOf("\\");

			if(idx_1 == idx_2) { // In the case "C:\\"
				this.directory = "";
			
			} else {  //In the case "C:\\Windows\\APPs\\"
				dir = dir.substring(0, dir.length()-1);
				dir = dir.substring(0, dir.lastIndexOf("\\")) + "\\";
				this.directory = dir;
			
			}

			this.refresh();
		} else {
			this.application.showToast("Invalid Operation");
		
		}
	}

	public void receiveMessage(TTClientMessage message) {
		if (message instanceof FileExploreResponseMessage) {
			FileExploreResponseMessage rm = (FileExploreResponseMessage) message;

			this.directory = rm.directory;

			this.fileInfos.clear();

			for (int i = 0; i < rm.fileInfos.length; i++) {
				FileInformationStruct fileInfo = new FileInformationStruct();
				fileInfo.path = rm.fileInfos[i].path;
				fileInfo.type = rm.fileInfos[i].type;

				fileInfos.add(fileInfo);
			}

			this.runOnUiThread(new Runnable() {
				public void run() {
					String str = FileExplorerActivity.this.GetShortPath(FileExplorerActivity.this.directory);
					if(str == "") {
						FileExplorerActivity.this.tvDirectory.setText("ROOT");
					} else {
						FileExplorerActivity.this.tvDirectory.setText(str);
					}

					FileExplorerActivity.this.adapter.notifyDataSetChanged();
					FileExplorerActivity.this.listView.setSelectionAfterHeaderView();
				}
			});
		}
	}

	private String GetShortPath(String path) {
		int nTotal = path.length();

		if(nTotal > 37) {
			return path.substring(0,3) + "...." + path.substring(path.length() - 30, path.length());
		} else {
			return path;
		}
	}

	/*
	private String GetShortPath(String path)
	{
		int nTotal = path.length();

		if(nTotal > 25)
		{
			int nStart = 3;

			char[] cArray = path.toCharArray();
			int lc = -1;
			int dem = 0;
			for(int i = nTotal - 1; i >= 0; i--)
			{
				if(cArray[i] == '\\')
					dem++;

				if(dem == 3)
				{
					lc = i;
					break;
				}
			}

			if(lc != -1)
			{
				String str1 = path.substring(0, nStart);
				String str2 = path.substring(lc,path.length());
				String str3 = str1 + "...." + str2;

				if(str3.length() > 50)
				{	// Chua coi ky truong hop nay nua
					return str3.substring(0,7) + str3.substring(str3.length() - 35, str3.length());
				}
				else
				{
					return str3;
				}
			}
			else
			{
				return path;
			}
		}
		else
		{
			return path;
		}
	}*/

	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		String path = this.fileInfos.get(position).path;
		int type = this.fileInfos.get(position).type;
		
		if(type == FileInformationStruct.FIXED || type == FileInformationStruct.FOLDER) {
			//Drive and Directory
			this.application.sendMessage(new FileExploreRequestMessage(GlobalVariables.getTemporaryKey(), path, ""));
		}
		
		if(type == FileInformationStruct.FILE) {
			//File
			//this.application.sendMessage(new FileExploreRequestMessage(GlobalVariables.getTemporaryKey(), "", path));
 		}
		
		this.application.vibrate(50);
	}

	private void refresh() {
		this.application.sendMessage(new FileExploreRequestMessage(GlobalVariables.getTemporaryKey(), this.directory, ""));
	}

	private void exploreRoots() {
		this.directory = "";
		refresh();
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {	
		if(keyCode ==  KeyEvent.KEYCODE_BACK) {
			if("".equals(this.directory) != true) {
				up();
			} else {
				this.finish();
			}
			
			return true;
		}
		
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onConnectionStateChanged() {
		this.refresh();
	}
	
	public void refreshConnection() {
		this.application.unregisterMessageReceiver(this);
		this.application.registerMessageReceiver(this);
		this.refresh();
	}
}